class NotesController < ApplicationController
  before_filter :login_required, :find_project
  
  def index
    @viewType = params[:view]
    if @viewType == "expanded"
      #fetch latest 10 messages
      @notes = @project ? @project.notes : Note.find(:all, :limit => 10, :order => "created_at desc")
      render(:template => "notes/index.expanded.html.erb")
    else
      @notes = @project ? @project.notes : Note.find(:all, :order => "created_at desc")
    end
    
    stop = 1
   
  end
  
  def new
    @note = Note.new
  end
  
  def create
    @note = Note.new(params[:note].merge(:project_id => params[:project_id]).merge(:user_id => session[:user]))

    @note.title.capitalize!
    @note.body.capitalize!
    
    if @note.save
      #create contacts to notes relationship
      n2c = @note.notes_contacts.create(:contact_id => params[:contact]['contact_id'])
      if !n2c
        #contacts are not created. Possibly we want to delete the note record
        #@question: is there any transaction management or referential integrity rules?
        @note.delete
        flash[:notice] = 'Note could not be created. Please try again'
        render :action => :new
      else
        flash[:notice] = 'Note successfully created.'
        redirect_to :action => :index
      end
    else
      render :action => :new
    end
  end
  
  def list
    #@notes = Note.find(:all , {:order => "updated_at DESC"})
    #changed to list just documents of selected project
    @notes = @project ? @project.notes : Note.find(:all)
    #list and index actions are identical. 
    render(:action => "index")
  end
  
  def show
    @note = Note.find(params[:id])
  end
  
  def edit
    @note = Note.find(params[:id])
    #session[:prev_page] = request.env["HTTP_REFERER"] 
    #@prev_page =  session[:prev_page].to_s
  end
  
  def update
    @note = Note.find(params[:id])
    params[:note]['title'].capitalize!
    params[:note]['body'].capitalize!
    
    if @note.update_attributes(params[:note])
      #create contacts to notes relationship
      n2c = @note.notes_contacts.create(:contact_id => params[:contact]['contact_id'])
      if !n2c
        #contacts cannot be created. Possibly we want to delete the note record
        #@question: is there any transaction management or referential integrity rules?
        @note.delete
        flash[:notice] = 'Note could not be created. Please try again'
        render :action => :new
      else
        flash[:notice] = "Note updated successfuly"
        redirect_to :action => :index
      end
    else
      render :action => :edit
    end  
  end
  
  def destroy
   @note = Note.find(params[:id])
   @note.destroy
   redirect_to :back
 end
 
 private
 def find_project
   @project = Project.find_by_id(params[:project_id])
 end
end
